﻿/*
 * LINQ to LDAP
 * http://linqtoldap.codeplex.com/
 * 
 * Copyright Alan Hatter (C) 2010-2012
 * alan.hatter@gmail.com - http://hattercoding.blogspot.com/
 * 
 * This project is subject to licensing restrictions. Visit http://linqtoldap.codeplex.com/license for more information.
 */

using System;
using System.IO;

namespace LinqToLdap.Logging
{
    /// <summary>
    /// A simple implementation of <see cref="ILinqToLdapLogger"/> that writes to a <see cref="TextWriter"/>.
    /// </summary>
    public class SimpleTextLogger : ILinqToLdapLogger
    {
        private readonly WeakReference _textWriter;

        /// <summary>
        /// Creates a new logger from a <see cref="TextWriter"/>.
        /// </summary>
        /// <param name="textWriter">The log destination</param>
        public SimpleTextLogger(TextWriter textWriter)
        {
            _textWriter = new WeakReference(textWriter);
            TraceEnabled = true;
        }

        /// <summary>
        /// Indicates if trace logging is enabled.
        /// </summary>
        public bool TraceEnabled { get; set; }

        /// <summary>
        /// Writes the message to the trace if <see cref="TraceEnabled"/> is true.
        /// </summary>
        /// <param name="message"></param>
        public void Trace(string message)
        {
            if (!_textWriter.IsAlive) throw new InvalidOperationException("The TextWriter associated with class has been garbage collected.");

            ((TextWriter)_textWriter.Target).WriteLine(message);
        }

        /// <summary>
        /// Writes the optional message and exception.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="ex">The exception.</param>
        public void Error(Exception ex, string message = null)
        {
            if (!_textWriter.IsAlive) throw new InvalidOperationException("The TextWriter associated with class has been garbage collected.");

            var writer = (TextWriter) _textWriter.Target;
            if (message != null) writer.WriteLine(message);
            ObjectDumper.Write(ex, 0, writer);
        }
    }
}
